﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Text;

namespace PowerGuiVsx.Module
{
    [Cmdlet(VerbsLifecycle.Start, "RemoteDebugger")]
    public class StartRemoteDebuggerCommand : PowerGuiVsxCommand
    {
        [Parameter(Mandatory=true)]
        public string ComputerName { get; set; }

        [Parameter]
        [Credential]
        public PSCredential Credential { get; set; }

        [Parameter]
        public SwitchParameter x64 { get; set; }

        protected override void BeginProcessing()
        {
            var currentProcess = Process.GetCurrentProcess();
            var devenvDirectory = new FileInfo(currentProcess.MainModule.FileName).Directory;
            string arch = x64.IsPresent ? "x64" : "x86";

            var remoteDebugger = Path.Combine(devenvDirectory.FullName, "Remote Debugger");
            remoteDebugger = Path.Combine(remoteDebugger, arch);

            var path = String.Format(@"\\{0}\C$\Windows\Temp\RemoteDebugger", ComputerName);

            try
            {
                ProcessUtils.CopyFolder(remoteDebugger, path, ComputerName, Credential.UserName, Credential.Password.ConvertToUnsecureString());
                ProcessUtils.StartRemoteProcess(@"C:\Windows\Temp\RemoteDebugger\msvsmon.exe", ComputerName, Credential.UserName, Credential.Password);
            }
            catch (Exception ex)
            {
                WriteError(ex);
                return;
            }
        }
    }

    public static class SecureStringExtension
    {
        public static string ConvertToUnsecureString(this SecureString securePassword)
        {
            if (securePassword == null)
                throw new ArgumentNullException("securePassword");

            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
    }
}
